<?php

include("ext/mime.php");
$sanitize_all_escapes = true;

//STOP FAKE REGISTER GLOBALS
$fake_register_globals = false;
//continue session
session_start();

//landing page definition -- where to go if something goes wrong
$landingpage = "index.php?site=" . $_SESSION['site_id'];
//
// kick out if patient not authenticated
if (isset($_SESSION['pid']) && isset($_SESSION['patient_portal_onsite'])) {
    $pid = $_SESSION['pid'];
} else {
    session_destroy();
    header('Location: ' . $landingpage . '&w');
    exit;
}

$ignoreAuth = true;
require_once('../../interface/globals.php');

$savedpath = $_SERVER['DOCUMENT_ROOT'] . "/expsac/sites/default/documents/" . $pid;
if (!is_dir($savedpath)) {
    mkdir($savedpath, 0777, true);
    chmod($savedpath, 0777);
}

define("_UPLOADS", $savedpath . "/");
define("_THUMBNAIL", "uploads/thumbnails/");

$img = file_get_contents('php://input');
$temp = explode(',', $img);
$img = $temp[1];
$t = time();
$categoria = $_SERVER['HTTP_CATEGORIA'];

$name = $_SERVER['HTTP_UPLOADER_NAME'];
$isThumb = $_SERVER['HTTP_UPLOADER_THUMB'];
$data = base64_decode($img);
$file = _UPLOADS . $t . "-" . $name;

$success = file_put_contents($file, $data);
$fsize = filesize($file);
$timeFile = filemtime($file);

$filetype = mimetype($file);
$currenthash = sha1_file( $file );

$isThumb = false; //No guardar thumbnail en el servidor
if ($isThumb == true && stristr($_SERVER['CONTENT_TYPE'], "image") == true) {
    $thumbWidth = $_SERVER['HTTP_UPLOADER_THUMBWIDTH'];
    $thumbHeight = $_SERVER['HTTP_UPLOADER_THUMBHEIGHT'];

    $newThumb = imagecreatetruecolor($thumbWidth, $thumbHeight);
    $thumbTemp = imagecreatefromstring($data);
    $thumb = imagecopyresampled($newThumb, $thumbTemp, 0, 0, 0, 0, $thumbWidth, $thumbHeight, imagesx($thumbTemp), imagesy($thumbTemp));

    $thumbFile = _THUMBNAIL . $t . $name;
    imagejpeg($newThumb, $thumbFile, 90);
}

if ($success) {
    $docdate = date("Y-m-d", $timeFile);
//    echo $pid . "-" . $fsize . "-" . $file . "-" . $docdate . "-" . $categoria . "-";
    guardar_documento($pid, $fsize, $file, $docdate, $categoria, $filetype, $currenthash);
    echo "true";
} else {
    echo "Server failed for file: " . $name;
}

function guardar_documento($patient_id, $fsize, $target, $docdate, $catid, $filetype, $currenthash) {
//        $fsize = filesize($target);
//        $catid = (int) $_POST['form_category'];
    // Update the database.
    $query = "INSERT INTO documents ( " .
            "type, size, date, url, mimetype, foreign_id, docdate, hash, source_entry" .
            " ) VALUES ( " .
            "'file_url', '$fsize', NOW(), 'file://$target', '" .
            $filetype . "', $patient_id, '$docdate', '$currenthash', '1' " .
            ")";
    
    $newid = sqlInsert($query);
    
    $query = "INSERT INTO categories_to_documents ( " .
            "category_id, document_id" .
            " ) VALUES ( " .
            "'$catid', '$newid' " .
            ")";
    sqlStatement($query);
    $encounter = $_SESSION['ecnounter'];
    if( $encounter  > 0 ){
        $query = " INSERT INTO documents_encounter ( document_id, encounter ) VALUES ( $newid,  $encounter) ";
    }else{
        $query = " INSERT INTO documents_encounter ( document_id, encounter ) VALUES ( $newid,  null ) ";
    }
    sqlStatement($query);
    
}

function mimetype($filepath) {
    // Check only existing files
    if (!file_exists($filepath) || !is_readable($filepath))
        return "NA";

    // Trying finfo
    if (function_exists('finfo_open')) {
        $finfo = finfo_open(FILEINFO_MIME);
        $mimeType = finfo_file($finfo, $filepath);
        finfo_close($finfo);
        // Mimetype can come in text/plain; charset=us-ascii form
        if (strpos($mimeType, ';'))
            list($mimeType, ) = explode(';', $mimeType);
        return $mimeType;
    }

    // Trying mime_content_type
    if (function_exists('mime_content_type')) {
        return mime_content_type($filepath);
    }

    // Trying exec
    if (function_exists('exec')) {
        $mimeType = exec("file -i -b $filepath");
        if (!empty($mimeType))
            return $mimeType;
    }

    // Trying to get mimetype from images
    $imageData = @getimagesize($filepath);
    if (!empty($imageData['mime'])) {
        return $imageData['mime'];
    }

    $mimetypes = array(
        'gif' => 'image/gif',
        'png' => 'image/png',
        'jpg' => 'image/jpg',
        'css' => 'text/css',
        'js' => 'text/javascript',
        'pdf' => 'application/pdf',
    );
    $path_parts = pathinfo($filepath);
    if (array_key_exists($path_parts['extension'], $mimetypes)) {
        return $mimetypes[$path_parts['extension']];
    } 

    return "application/octet-stream";
}

?>